package com.stylefeng.guns.core.util.excel;


import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

import java.util.List;

/**
 * excel导出组件 .xls后缀
 *
 * @author carloszhang
 */
public abstract class ExportExcelXlsComponent<T> {

    protected transient Logger LOG = LoggerFactory.getLogger(this.getClass());

    public static final String EXCEL_PATH = "com/stylefeng/guns/core/util/excel/template.xls";

    /**
     * 构建头信息
     */
    private void buildExcelHeader(HSSFSheet sheet, List<String> headers) {
        HSSFRow row = sheet.createRow(0);// 创建表头
        int titleCellIndex = 0;
        HSSFCell cell = null;
        for (String headerValue : headers) {
            cell = row.createCell(titleCellIndex);
            cell.setCellValue(StringUtils.trimToEmpty(headerValue));
            // sheet.autoSizeColumn(titleCellIndex, true);
            sheet.setColumnWidth(titleCellIndex, (int)((12 + 0.72) * 256));
            titleCellIndex++;
        }
    }

    /**
     * 构建数据
     */
    protected abstract void buildExcelDatas(HSSFSheet sheet, List<T> datas);

    /**
     * 构建Excel
     */
    private HSSFWorkbook buildExcel(List<String> headers, List<T> datas) {
        try {
            ClassPathResource resource = new ClassPathResource(EXCEL_PATH);
            HSSFWorkbook workbook = new HSSFWorkbook(resource.getInputStream());
            HSSFSheet sheet = workbook.getSheetAt(0);
            sheet.autoSizeColumn(1, true);
            sheet.createFreezePane(0, 1, 0, 1);
            buildExcelHeader(sheet, headers);
            buildExcelDatas(sheet, datas);
            return workbook;
        } catch (Exception e) {
            LOG.error("构建excel失败", e);
        }
        return null;
    }

    /**
     * 构建excel头信息
     */
    protected abstract List<String> buildHeader();

    public HSSFWorkbook buildExportExcel(List<T> datas) {
        return buildExcel(buildHeader(), datas);
    }

    protected String trimData(Object object) {
        return object == null ? StringUtils.EMPTY : String.valueOf(object);
    }

    protected HSSFCell createCell(HSSFRow row, int conCellIndex) {
        return row.createCell(conCellIndex);
    }

}
